﻿/**************************************************************
 *
 * 唯一标识：410765c8-463b-47e3-912c-acd0d4f35e85
 * 命名空间：Sgr.UPMS.Application.Commands.Roles
 * 创建时间：2023/8/27 17:41:28
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：更新角色命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.UPMS.Domain.Roles;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Roles
{
    /// <summary>
    /// 更新角色命令处理器
    /// </summary>
    public class UpdateRoleCommandHandle : IRequestHandler<UpdateRoleCommand, CommandResult<bool>>
    {
        private readonly IRoleRepository _roleRepository;
        private readonly IRoleManage _roleManage;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="roleRepository">角色仓储</param>
        /// <param name="roleManage">角色管理器</param>
        public UpdateRoleCommandHandle(IRoleRepository roleRepository, IRoleManage roleManage)
        {
            _roleRepository = roleRepository;
            _roleManage = roleManage;
        }

        /// <summary>
        /// 处理更新角色命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            // 查找角色实体
            var role = await _roleRepository.GetAsync(request.RoleId, cancellationToken);

            // 如果找不到角色，返回NotFound结果
            if (role == null)
                return CommandResult.NotFound<bool>("未找到指定的角色");

            // 更新角色名称
            await _roleManage.ChangeNameAsync(role, request.RoleName, cancellationToken);

            // 更新角色其他信息
            role.Remarks = request.Remarks;
            role.OrderNumber = request.OrderNumber;
            role.ChangeEntityStates(request.State);

            // 更新到仓储
            await _roleRepository.UpdateAsync(role, cancellationToken);

            // 返回成功结果
            return CommandResult.Success(true, "角色信息更新成功");
        }
    }
}